import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createPage, base, ajax, toast, RenderRouter } from 'nc-lightapp-front';
import { initTemplate, afterEvent, searchClick } from './events';

import requestApi from './requestApi'
import './index.less';

import RepaymentBillCard from '../../repaymentExt/card/repaymentBillCard';
import {
    ProfileStyle,
    ProfileHead,
    ProfileBody,
    EmptyArea
} from 'ssccommon/components/profile';
import { setForm } from 'ssccommon/utils/setComponentUsed'
import presetVar from './presetVar';

class RepaymentForPull extends Component {
    constructor(props) {
        super(props);
        setForm(props, '20110ETLB')
        window.addEventListener('hashchange', () => {
            console.log('3333');
        })

        this.tzd
        let { form, button, table, editTable, search } = this.props;
        let { setSearchValue, setSearchValByField, getAllSearchData } = search;
        this.setSearchValByField = setSearchValByField;//设置查询区某个字段值
        this.getAllSearchData = getAllSearchData;//获取查询区所有字段数据

        this.isError = false; //转单编辑后字段是否通过验证
        //到账通知信息
        this.dztz = {
            billno: props.getUrlParam('vbillno'),//单据号
            billid: props.getUrlParam('pk'),//单据主键
            batch: props.getUrlParam('transerial'),//交易流水号
            summary: props.getUrlParam('memo'),//摘要
            amount: props.getUrlParam('moneyy'),//金额
            //amount: 112,//金额
        };

        initTemplate.call(this, props);

    }
    setRowCheckedByDZTZ(data) {
        let selectRowPks = [];
        data && 
        data.length && 
        data.forEach((eachRow)=>{
            eachRow && 
            eachRow.body && 
            eachRow.body.jk_busitem && 
            eachRow.body.jk_busitem.rows && 
            eachRow.body.jk_busitem.rows.forEach((bodyRow)=>{
                if(bodyRow && 
                    bodyRow.values && 
                    bodyRow.values.hkybje && 
                    bodyRow.values.hkybje.value &&
                    bodyRow.values.hkybje.value > 0){
                        let selectRowPk = bodyRow.values.pk_busitem.value;
                        selectRowPks.push(selectRowPk);
                }
            })
        })
        this.props.transferTable.setTheCheckRows(presetVar.areaCode.billsArea, selectRowPks);
    }
    componentDidMount() {

        let { hasCache } = this.props.transferTable;

        console.log(8888, hasCache('ssc.erm.repayment.pull'));

        if (hasCache('ssc.erm.repayment.pull_ID')) {
            /* ajax({
                url:"...",
                data:"...",
                success:(res)=>{
                    if(res && res.data && res.data["tableAreacode"]){
                         this.props.table.setAllTableData(res.data["tableAreacode"]);
                    }
                }
            }) */
        }


        // this.props.transferTable.setTransferTableValue(presetVar.areaCode.billsArea, presetVar.areaCode.bodysArea, [], 'pk_jkbx', 'pk_busitem');
    }

    render() {
        let { form, button, table, editTable, search, transferTable } = this.props;
        let { NCCreateSearch } = search;
        let { createButton } = button;
        let { createEditTable } = editTable;
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let { createTransferTable } = transferTable;

        let isShowSelectedList = transferTable.getSelectedListDisplay(presetVar.areaCode.billsArea);
        return (
            <div id='repayment-for-pull'><ProfileStyle
                layout="singleTable"
                {...this.props}
            >
                {isShowSelectedList ?
                    null
                    :
                    (
                        <ProfileHead
                            // "201102HKD-0001": "还款单"
                            title={multiLang && multiLang.get('201102HKD-0001')}
                        >
                        </ProfileHead>
                    )
                }

                <ProfileBody>
                    {
                        isShowSelectedList ?
                            null
                            :
                            (
                                <EmptyArea className="ssc-profile-search-area">

                                    {NCCreateSearch(
                                        '20110ETLB',//模块id
                                        {
                                            clickSearchBtn: searchClick.bind(this),//   点击按钮事件
                                            defaultConditionsNum: 2, //默认显示几个查询条件
                                            onAfterEvent: afterEvent()//编辑后事件
                                        }
                                    )}
                                </EmptyArea>
                            )
                    }

                    <EmptyArea>
                        {createTransferTable(
                            {
                                editStatus: true,
                                dataSource: 'ssc.erm.repayment.pull',
                                headTableId: presetVar.areaCode.billsArea,//表格组件id
                                bodyTableId: presetVar.areaCode.bodysArea,//子表模板id
                                fullTableId: presetVar.areaCode.bodysArea,//主子拉平模板id
                                //点击加号展开，设置表格数据
                                // "201102HKD-0004": "生成还款单",
                                transferBtnText: multiLang && multiLang.get('201102HKD-0004'), //转单按钮显示文字
                                containerSelector: '#transferDemo', //容器的选择器 必须唯一,用于设置底部已选区域宽度
                                cacheItem: ['hkybje'], //缓存字段
                                editableItem: ['hkybje'], //可编辑字段
                                afterEvent: (attrcode, value, record, index) => {
                                    console.log('编辑后事件', attrcode, value, record, index);

                                    switch (attrcode) {
                                        case 'hkybje':
                                            if (+value > +record.yjye.value) { //这里写具体的业务判断条件
                                                //修改失败，输入的金额有误
                                                toast({ content: multiLang && multiLang.get('201102HKD-0005'), color: 'danger' });
                                                this.isError = true;
                                            } else {
                                                if (!value) {
                                                    let data = record;
                                                    data['hkybje'].value = '0';
                                                    this.props.transferTable.setRowDataByIndex('head', data, data.rowIndex);
                                                }
                                                if (+value == 0) {
                                                    //还款金额不能为0
                                                    toast({ content: multiLang && multiLang.get('201102HKD-0006'), color: 'danger' });
                                                    this.isError = true;
                                                } else {
                                                    this.isError = false;
                                                }
                                            }
                                            break;
                                    }
                                }, //编辑后事件
                                onTransferBtnClick: (ids) => {//点击转单按钮钩子函数
                                    // "201102HKD-0005": "修改失败，输入的金额有误",
                                    if (this.isError) {
                                        toast({
                                            content: multiLang && multiLang.get('201102HKD-0005'),
                                            color: 'danger'
                                        });
                                    } else {
                                        let continueFlag = true;
                                        if (this.dztz.amount) {
                                            let selectedamount = 0;
                                            ids.forEach((bill) => {
                                                bill.bodys.forEach((body) => {
                                                    selectedamount = selectedamount + parseFloat(body.hkybje.value)
                                                })
                                            })

                                            if ((+selectedamount) != this.dztz.amount) {
                                                toast({
                                                    content: multiLang && multiLang.get('201102HKD-0010'),//'还款金额必须等于到账通知金额！',
                                                    color: 'danger'
                                                });
                                                continueFlag = false;
                                            }
                                        }

                                        if (continueFlag) {
                                            this.props.pushTo("/card", {
                                                addtype: 'pull',
                                                status: 'add',
                                                pagecode: '201102HKD_card_002',
                                                dztz_summary: this.dztz.summary,
                                                dztz_batch: this.dztz.batch,
                                                dztz_billno: this.dztz.billno,
                                                dztz_billid: this.dztz.billid,
                                                dztz_money: this.dztz.amount
                                            });
                                        }
                                    }
                                },
                            }
                        )}
                    </EmptyArea>
                </ProfileBody>
            </ProfileStyle>
            </div>
        )
    }
}

RepaymentForPull = createPage({
    mutiLangCode: '2011'
})(RepaymentForPull)

// export default RepaymentForPull;

const routes = [
    {
        path: '/pull',
        component: RepaymentForPull
    },
    {
        path: '/card',
        component: RepaymentBillCard
    }
];


(function main(routers, htmlTagid) {
    RenderRouter(routers, htmlTagid);
})(routes, "app");
window.aabb = 12
//ReactDOM.render(<RepaymentForPull />, document.querySelector('#app'))
